﻿using Newtonsoft.Json;
using PMS.Common;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace PMS.Logic.CM
{
    public partial class QuotationAjax : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            String methodName = Request["method"];
            Type type = this.GetType();
            MethodInfo method = type.GetMethod(methodName);
            if (methodName == null) throw new Exception("method is null!");
            try
            {
                method.Invoke(this, null);
            }
            catch
            {
                throw;
            }
        }


        /* 
         * 报价单相关函数
        */

        /// <summary>
        /// 获取报价单信息
        /// </summary>
        public void GetQuotationList()
        {
            List<SearchCondition> listSearch = new List<SearchCondition>();
            if (Request.Form["searchData"] != null)
            {
                string searchData = Request.Form["searchData"];
                listSearch = ModelTools.GetSearchContions(searchData);
            }
            Expression<Func<View_CM_Quotation, bool>> exp = SearchExpression.FindByGroup<View_CM_Quotation>(listSearch);
            //string OrderId = OperateContext.Sort == null ? "State" : OperateContext.Sort;
            string OrderId = OperateContext.Sort == null ? "ID" : OperateContext.Sort;
            Boolean OrderSort = OperateContext.Order == false ? OperateContext.Order : false;
            int count = 0;
            var list = DALSession.Current.View_CM_QuotationDAL.GetPagedList(OperateContext.Page, OperateContext.Rows, exp, OrderId, OrderSort);
            count = DALSession.Current.View_CM_QuotationDAL.GetCount(exp);
            Response.Write(JsonHelper.toPageJson(list, count));
        }

        public void GetQuotationDetail()
        {
            int qID = Convert.ToInt32(Request.Form["Id"].ToString());
            View_CM_Quotation res = DALSession.Current.View_CM_QuotationDAL.GetListBy(u => u.ID == qID).FirstOrDefault();
            Response.Write(JsonHelper.toJson(res));
        }

        /// <summary>
        /// 修改报价单信息
        /// </summary>
        public void EditQuotation()
        {
            Boolean res = true;
            String msg = "";
            int ID = Commons.String2Int32(Request.Form["ID"]);
            CM_Quotation perNew = DALSession.Current.CM_QuotationDAL.GetListBy(d => d.ID == ID).FirstOrDefault();
            ModelTools.Form2EditModel(Request.Form, perNew);
            if (checkQuotation(perNew, msg))
            {
                DALSession.Current.CM_QuotationDAL.ModifyAllModel(perNew);
                DALSession.Current.CM_QuotationDAL.SaveChanges();
                msg = "保存成功！";
            }
            else
            {
                res = false;
            }
            Response.Write(JsonHelper.toDefaultMsg(res, ID.ToString()));
        }

        /// <summary>
        /// 添加报价单信息
        /// </summary>
        public void AddQuotation()
        {
            Boolean res = true;
            String msg = "";
            String Id = "0";
            CM_Quotation per = new CM_Quotation();
            ModelTools.Form2EditModel(Request.Form, per);
            //生成流水号 BJyyMMdd0002
            string newId = "BJ";
            string time = DateTime.Now.ToString("yyMMdd");
            var con = DALSession.Current.CM_QuotationDAL.GetListBy(c => c.Code.Substring(2, 6) == time, p => p.Code, false).FirstOrDefault();
            if (con == null)
            {
                newId += time + "0001";
            }
            else
            {
                newId += time + (Commons.String2Int32(con.Code.Substring(8, 4)) + 1).ToString().PadLeft(4, '0');
            }
            per.Code = newId;
            per.State = "0";
            if (checkQuotation(per, msg))
            {
                //DALSession.Current.CM_QuotationDAL.Add(per);
                Id = DALSession.Current.CM_QuotationDAL.AddModelReturnId(per, "ID");
                DALSession.Current.CM_QuotationDAL.SaveChanges();
                msg = "保存成功！";
            }
            else
            {
                res = false;
            }
            Response.Write(JsonHelper.toDefaultMsg(res, Id));
        }

        /// <summary>
        /// 删除报价单信息
        /// </summary>
        public void DelQuotation()
        {
            int Id = Convert.ToInt32(Request.Form["Id"].ToString());

            //删除报价单
            DALSession.Current.CM_QuotationDAL.DelBy(u => u.ID == Id);
            DALSession.Current.CM_QuotationDAL.SaveChanges();

            //获取报价单的产品细则
            List<CM_QuotationDetail> pDlist = DALSession.Current.CM_QuotationDetailDAL.GetListBy(u => u.QuotationID == Id).ToList();

            //删除产品细则
            pDlist.ForEach(pOut =>
            {
                DALSession.Current.CM_QuotationDetailDAL.DelBy(pIn => pIn.ID == pOut.ID);
            });
            DALSession.Current.CM_QuotationDetailDAL.SaveChanges();

            //删除产品细则的技术参数
            pDlist.ForEach(pOut =>
            {
                DALSession.Current.CM_QuotationDetailDetailDAL.DelBy(pIn => pIn.QuotationDetailID == pOut.ID);
            });
            DALSession.Current.CM_QuotationDetailDetailDAL.SaveChanges();

            Response.Write(JsonHelper.toDefaultMsg(true, "删除成功"));
        }

        /*
         产品细则相关函数
         */

        /// <summary>
        /// 获取报价单qID的所有产品细则
        /// </summary>
        public void GetProductionDetail()
        {
            int qID = Convert.ToInt32(Request.Form["Id"].ToString());
            List<CM_QuotationDetail> list = DALSession.Current.CM_QuotationDetailDAL.GetListBy(u => u.QuotationID == qID).ToList();
            Response.Write(JsonHelper.toJson(list));
        }

        /// <summary>
        /// 根据产品细则ID查询产品细则
        /// </summary>
        public void GetProductionDetailByID()
        {
            if (Request["id"] != null)
            {
                int id = Commons.String2Int32(Request["id"]);

                CM_QuotationDetail list = DALSession.Current.CM_QuotationDetailDAL.GetListBy(u => u.ID == id).FirstOrDefault();

                Response.Write(JsonHelper.toJson(list));
            }
        }

        /// <summary>
        /// 添加或修改产品细则
        /// </summary>
        public void AddProductionDetail()
        {
            Boolean res = true;
            String msg = "";
            CM_QuotationDetail pd = new CM_QuotationDetail();
            ModelTools.Form2Model(Request.Form, pd);
            if (String.IsNullOrEmpty(pd.ProductName))
            {
                pd.ProductName = "";
            }
            if (checkQuotationDetail(pd, msg))
            {
                if (AddQuotationDetail(pd, "add"))
                {
                    msg = "保存成功！";
                }
                else
                {
                    res = false;
                }
            }
            else
            {
                res = false;
            }
            Response.Write(JsonHelper.toDefaultMsg(res, msg));
        }

        /// <summary>
        /// 删除报价单产品细则
        /// </summary>
        public void DelProductionDetail()
        {
            int Id = Convert.ToInt32(Request.Form["Id"].ToString());

            //删除产品细则
            DALSession.Current.CM_QuotationDetailDAL.DelBy(p => p.ID == Id);
            DALSession.Current.CM_QuotationDetailDAL.SaveChanges();

            //删除产品细则的技术参数
            DALSession.Current.CM_QuotationDetailDetailDAL.DelBy(p => p.QuotationDetailID == Id);
            DALSession.Current.CM_QuotationDetailDetailDAL.SaveChanges();

            Response.Write(JsonHelper.toDefaultMsg(true, "删除成功"));
        }

        /// <summary>
        /// 保存报价单细则
        /// </summary>
        public void saveProductionDetail()
        {
            Boolean res = false;
            String msg = "";
            string dataString = Request.Form["data"];
            if (String.IsNullOrEmpty(dataString))
            {
                res = false;
                msg = "保存失败！";
            }
            else
            {
                res = true;
                msg = "保存成功";
                List<CM_QuotationDetail> detailList = JsonConvert.DeserializeObject<List<CM_QuotationDetail>>(dataString);
                detailList.ForEach(qd =>
                {
                    CM_QuotationDetail oldQD = DALSession.Current.CM_QuotationDetailDAL.GetListBy(li => li.ID == qd.ID).FirstOrDefault();
                    //判断原产品细则是否有名称
                    if (null != oldQD.ProductName && "" != oldQD.ProductName)
                    {
                        if (oldQD.ProductName.Equals(qd.ProductName))
                        {
                            if (ChangeEmptyToNull(qd))
                            {
                                DALSession.Current.CM_QuotationDetailDAL.ModifyBy(qd, temp => temp.ID == qd.ID, "IsPureGas", "BottleVolume", "unit", "OrderCount", "SinglePrice", "BottleCount", "BottlePrice", "TotalPrice", "TotalPrice", "IsNewBottle", "Note", "OrderCode", "StockCode", "PurchaseType", "ApplyPerson");
                            }
                        }
                        else
                        {
                            //删除之前的技术参数信息
                            DALSession.Current.CM_QuotationDetailDetailDAL.DelBy(li => li.QuotationDetailID == oldQD.ID);
                            if (AddQuotationDetail(qd, "edit"))
                            {
                                if (ChangeEmptyToNull(qd))
                                {
                                    DALSession.Current.CM_QuotationDetailDAL.ModifyBy(qd, temp => temp.ID == qd.ID, "ProductName", "IsPureGas", "BottleVolume", "unit", "OrderCount", "SinglePrice", "BottleCount", "BottlePrice", "TotalPrice", "TotalPrice", "IsNewBottle", "Note", "OrderCode", "StockCode", "PurchaseType", "ApplyPerson");
                                }
                            }
                            else
                            {
                                res = false;
                                msg = "保存失败！";
                            }
                        }
                    }
                    else
                    {
                        //没有名称直接更新名称及细则
                        if (AddQuotationDetail(qd, "edit"))
                        {
                            if (ChangeEmptyToNull(qd))
                            {
                                DALSession.Current.CM_QuotationDetailDAL.ModifyBy(qd, temp => temp.ID == qd.ID, "ProductName", "IsPureGas", "BottleVolume", "unit", "OrderCount", "SinglePrice", "BottleCount", "BottlePrice", "TotalPrice", "TotalPrice", "IsNewBottle", "Note", "OrderCode", "StockCode", "PurchaseType", "ApplyPerson");
                            }
                        }
                        else
                        {
                            res = false;
                            msg = "保存失败！";
                        }
                    }
                }
                );
                DALSession.Current.CM_QuotationDetailDAL.SaveChanges();
            }
            Response.Write(JsonHelper.toDefaultMsg(res, msg));
        }
        /// <summary>
        /// 通过Excel导入报价单细则
        /// </summary>
        //public void ImportQuotationDetail()
        //{
        //    StringBuilder errorMsg = new StringBuilder(); // 错误信息
        //    String filePath = "";
        //    try
        //    {
        //        #region 1.获取Excel文件并转换为一个List集合
        //        // 1.1存放Excel文件到本地服务器
        //        HttpPostedFile filePost = Request.Files["filed"]; // 获取上传的文件
        //        filePath = ExcelHelper.SaveExcelFile(filePost); // 保存文件并获取文件路径
        //        int Id = Commons.String2Int32(Request["Id"]);
        //        // 单元格抬头
        //        // key：实体对象属性名称，可通过反射获取值
        //        // value：属性对应的中文注解
        //        Dictionary<string, string> cellheader = new Dictionary<string, string> { 
        //            { "QuotationID", "报价单ID" }, 
        //            { "ProductName", "产品名称" }, 
        //            { "BottleVolume", "规格" }, 
        //            { "unit", "单位" }, 
        //            { "OrderCount", "计划数量" }, 
        //            { "SinglePrice", "单价" },
        //            { "TotalPrice", "总价" },
        //            { "IsNewBottle", "是否新瓶" },
        //            {"IsPureGas","是否纯气"},
        //            { "OrderCode", "订单编号" },
        //            { "StockCode", "存货编号" },
        //            { "PurchaseType", "采购类型" },
        //            { "ApplyPerson", "使用人员" },
        //            { "Note", "备注" }
        //        };
        //        // 1.2解析文件，存放到一个List集合里
        //        List<CM_QuotationDetail> enlist = ExcelHelper.ExcelToEntityList<CM_QuotationDetail>(cellheader, filePath, out errorMsg);
        //        #endregion

        //        #region 2.对List集合进行有效性校验
        //        for (int i = enlist.Count - 1; i >= 0; i--)
        //        {
        //            CM_QuotationDetail en = enlist[i];
        //            string errorMsgStr = "第" + (i + 1) + "行数据检测异常：";
        //            bool isHaveNoInputValue = false; // 是否含有未输入项
        //            if (string.IsNullOrEmpty(en.QuotationID.ToString()) || "0".Equals(en.QuotationID.ToString()) || Id != Commons.String2Int32(en.QuotationID.ToString()))
        //            {
        //                enlist.Remove(enlist[i]);
        //                errorMsgStr += "报价单ID与当前报价单ID不符；";
        //                isHaveNoInputValue = true;
        //            }
        //            if (isHaveNoInputValue) // 若必填项有值未填
        //            {
        //                errorMsg.AppendLine(errorMsgStr);
        //            }
        //        }
        //        #endregion

        //        // 3.TODO：对List集合进行持久化存储操作。如：存储到数据库
        //        enlist.ForEach(li =>
        //        {
        //            if ("新瓶".Equals(li.IsNewBottle))
        //            {
        //                li.IsNewBottle = "0";
        //            }
        //            else
        //            {

        //                li.IsNewBottle = "1";
        //            }
        //            if ("纯气体".Equals(li.IsPureGas))
        //            {
        //                li.IsPureGas = "1";
        //            }
        //            else
        //            {

        //                li.IsPureGas = "0";
        //            }
        //        });
        //        enlist.ForEach(li => DALSession.Current.CM_QuotationDetailDAL.Add(li));
        //        DALSession.Current.CM_QuotationDetailDAL.SaveChanges();
        //        // 4.返回操作结果
        //        bool isSuccess = false;
        //        if (errorMsg.Length == 0)
        //        {
        //            isSuccess = true; // 若错误信息成都为空，表示无错误信息
        //            errorMsg.Append("数据导入成功,共计导入" + enlist.Count() + "条。");
        //        }
        //        Response.Write(JsonHelper.toDefaultMsg(isSuccess, errorMsg.ToString())); // 返回Json格式的内容
        //    }
        //    catch (Exception ex)
        //    {
        //        Response.Write(JsonHelper.toDefaultMsg(false, ex.Message)); // 返回Json格式的内容
        //    }
        //    finally
        //    {
        //        File.Delete(filePath);
        //    }
        //}

        /// <summary>
        /// 同时添加多个产品
        /// </summary>
        public void AddMultiQuotationDetail()
        {
            int count = Convert.ToInt32(Request["Count"].ToString());
            Boolean res = true;
            String msg = "";
            CM_QuotationDetail pd = new CM_QuotationDetail();
            ModelTools.Form2Model(Request.Form, pd);
            if (checkQuotationDetail(pd, msg))
            {
                for (int i = 0; i < count; i++)
                {
                    res = AddQuotationDetail(pd, "add");
                }
                if (res)
                {
                    msg = "保存成功！";
                }
                else
                {
                    res = false;
                }
            }
            else
            {
                res = false;
            }
            Response.Write(JsonHelper.toDefaultMsg(res, msg));
        }

        /// <summary>
        /// 添加产品细则及技术参数
        /// </summary>
        /// <param name="pd"></param>
        /// <returns></returns>
        public Boolean AddQuotationDetail(CM_QuotationDetail pd, String action)
        {
            Boolean res = false;
            if (String.IsNullOrEmpty(pd.ProductName) && "add".Equals(action))
            {
                pd.ProductName = "";
                DALSession.Current.CM_QuotationDetailDAL.Add(pd);
                DALSession.Current.CM_QuotationDetailDAL.SaveChanges();
                res = true;
            }
            else
            {
                try
                {
                    int id = 0;
                    if ("add".Equals(action))
                    {
                        //新增报价单细则
                        id = Convert.ToInt32(DALSession.Current.CM_QuotationDetailDAL.AddModelReturnId(pd, "ID"));
                    }
                    else
                    {
                        id = pd.ID;
                    }
                    String prodName = pd.ProductName;
                    if (prodName.Contains("中"))
                    {
                        //添加组分技术参数
                        String comGasName = prodName.Substring(prodName.IndexOf("中") + 1);
                        String[] comGass = comGasName.Split('、');
                        foreach (String str in comGass)
                        {
                            BD_GasInfo gasInfo2 = DALSession.Current.BD_GasInfoDAL.GetListBy(ga => ga.GasChiName.Equals(str)).FirstOrDefault();
                            if (null != gasInfo2)
                            {
                                CM_QuotationDetailDetail comGas = new CM_QuotationDetailDetail();
                                comGas.QuotationDetailID = id;
                                comGas.GasID = gasInfo2.ID;
                                comGas.CusConcen = 0;
                                comGas.Concentration = 0;
                                comGas.CusUnit = "0";
                                comGas.IsBottomGas = "0";
                                comGas.Tolerance = 0;
                                // comGas.Note = "";
                                DALSession.Current.CM_QuotationDetailDetailDAL.Add(comGas);
                                DALSession.Current.CM_QuotationDetailDetailDAL.SaveChanges();
                            }
                        }

                        //添加底气技术参数
                        String botGasName = prodName.Substring(0, prodName.IndexOf("中"));
                        if ("空气".Equals(botGasName))
                        {
                            //添加氮气
                            BD_GasInfo gasInfo2 = DALSession.Current.BD_GasInfoDAL.GetListBy(ga => ga.GasChiName.Equals("氮气")).FirstOrDefault();
                            if (null != gasInfo2)
                            {
                                CM_QuotationDetailDetail comGas = new CM_QuotationDetailDetail();
                                comGas.QuotationDetailID = id;
                                comGas.GasID = gasInfo2.ID;
                                comGas.CusConcen = 0;
                                comGas.Concentration = 0;
                                comGas.CusUnit = "0";
                                comGas.IsBottomGas = "1";
                                comGas.Tolerance = 0;
                                //comGas.Note = "";
                                DALSession.Current.CM_QuotationDetailDetailDAL.Add(comGas);
                                DALSession.Current.CM_QuotationDetailDetailDAL.SaveChanges();
                            }
                            //添加氧气
                            BD_GasInfo gasInfo3 = DALSession.Current.BD_GasInfoDAL.GetListBy(ga => ga.GasChiName.Equals("氧气")).FirstOrDefault();
                            if (null != gasInfo3)
                            {
                                CM_QuotationDetailDetail comGas = new CM_QuotationDetailDetail();
                                comGas.QuotationDetailID = id;
                                comGas.GasID = gasInfo3.ID;
                                comGas.CusConcen = 0;
                                comGas.Concentration = 0;
                                comGas.CusUnit = "0";
                                comGas.IsBottomGas = "0";
                                comGas.Tolerance = 0;
                                //comGas.Note = "";
                                DALSession.Current.CM_QuotationDetailDetailDAL.Add(comGas);
                                DALSession.Current.CM_QuotationDetailDetailDAL.SaveChanges();
                            }
                        }
                        else
                        {
                            BD_GasInfo gasInfo = DALSession.Current.BD_GasInfoDAL.GetListBy(ga => ga.GasChiName.Equals(botGasName)).FirstOrDefault();
                            if (null != gasInfo)
                            {
                                CM_QuotationDetailDetail botGas = new CM_QuotationDetailDetail();
                                botGas.QuotationDetailID = id;
                                botGas.GasID = gasInfo.ID;
                                botGas.Concentration = 0;
                                botGas.CusConcen = 0;
                                botGas.CusUnit = "0";
                                botGas.IsBottomGas = "1";
                                botGas.Tolerance = 0;
                                //botGas.Note = "";
                                DALSession.Current.CM_QuotationDetailDetailDAL.Add(botGas);
                                DALSession.Current.CM_QuotationDetailDetailDAL.SaveChanges();
                            }
                        }
                        res = true;
                    }
                    else
                    {
                        res = true;
                    }
                }
                catch (Exception)
                {
                    res = false;
                }
            }
            return res;
        }

        /*
         产品细则技术参数相关函数
        */

        /// <summary>
        /// 
        /// </summary>
        public void GetProdTechParam()
        {
            int qID = Convert.ToInt32(Request.Form["Id"].ToString());
            List<View_CM_QuotationDetailDetail> list = DALSession.Current.View_CM_QuotationDetailDetailDAL.GetListBy(u => u.QuotationDetailID == qID).ToList();
            Response.Write(JsonHelper.toJson(list));
        }

        /// <summary>
        ///添加或修改产品细则技术参数 
        /// </summary>
        public void AddProdTechParam()
        {
            Boolean res = true;
            String msg = "";
            CM_QuotationDetailDetail role = new CM_QuotationDetailDetail();
            ModelTools.Form2Model(Request.Form, role);
            if (checkQuotationDetailDetail(role, msg))
            {
                CalculateConcentration(role);
                DALSession.Current.CM_QuotationDetailDetailDAL.Add(role);
                DALSession.Current.CM_QuotationDetailDetailDAL.SaveChanges();
                msg = "保存成功";
            }
            else
            {
                res = false;
            }
            Response.Write(JsonHelper.toDefaultMsg(res, msg));
        }

        /// <summary>
        /// 删除产品细则技术参数
        /// </summary>
        public void DelProdTechParam()
        {
            int Id = Convert.ToInt32(Request.Form["Id"].ToString());
            DALSession.Current.CM_QuotationDetailDetailDAL.DelBy(p => p.ID == Id);
            DALSession.Current.CM_QuotationDetailDetailDAL.SaveChanges();
            Response.Write(JsonHelper.toDefaultMsg(true, "删除成功"));
        }

        /// <summary>
        /// 保存技术参数
        /// </summary>
        public void saveProdTechParam()
        {
            string dataString = Request.Form["data"];
            List<CM_QuotationDetailDetail> detailList = JsonConvert.DeserializeObject<List<CM_QuotationDetailDetail>>(dataString);
            detailList.ForEach(li =>
            {
                CalculateConcentration(li);
                if (ChangeEmptyToNull(li))
                {
                    DALSession.Current.CM_QuotationDetailDetailDAL.Modify(li, "GasID", "Concentration", "CusConcen", "CusUnit", "IsBottomGas", "Tolerance", "Note");
                }
            });
            DALSession.Current.CM_QuotationDetailDetailDAL.SaveChanges();
            Response.Write(JsonHelper.toDefaultMsg(true, "保存成功"));
        }

        /// <summary>
        /// 通过Excel导入技术参数
        /// </summary>
        //public void ImportQuotationDetailDetail()
        //{
        //    StringBuilder errorMsg = new StringBuilder(); // 错误信息
        //    String filePath = "";
        //    try
        //    {
        //        #region 1.获取Excel文件并转换为一个List集合
        //        // 1.1存放Excel文件到本地服务器
        //        HttpPostedFile filePost = Request.Files["filed"]; // 获取上传的文件
        //        filePath = ExcelHelper.SaveExcelFile(filePost); // 保存文件并获取文件路径
        //        // 单元格抬头
        //        // key：实体对象属性名称，可通过反射获取值
        //        // value：属性对应的中文注解
        //        Dictionary<string, string> cellheader = new Dictionary<string, string> { 
        //            { "QuotationDetailID", "报价单细则ID" }, 
        //            { "GasID", "气体ID" }, 
        //            { "CusConcen", "气体浓度" }, 
        //            {"CusUnit","浓度单位"},
        //            {"Tolerance","误差容忍度"},
        //            {"IsBottomGas","是否底气"},
        //            { "Note", "备注" }
        //        };
        //        // 1.2解析文件，存放到一个List集合里
        //        List<CM_QuotationDetailDetail> enlist = ExcelHelper.ExcelToEntityList<CM_QuotationDetailDetail>(cellheader, filePath, out errorMsg);
        //        #endregion

        //        #region 2.对List集合进行有效性校验
        //        for (int i = enlist.Count - 1; i >= 0; i--)
        //        {
        //            CM_QuotationDetailDetail en = enlist[i];
        //            string errorMsgStr = "第" + (i + 1) + "行数据检测异常：";
        //            bool isHaveNoInputValue = false; // 是否含有未输入项
        //            if (string.IsNullOrEmpty(en.QuotationDetailID.ToString()))
        //            {
        //                errorMsgStr += "报价单细则ID不能为空；";
        //                isHaveNoInputValue = true;
        //            }
        //            if (string.IsNullOrEmpty(en.GasID.ToString()))
        //            {
        //                errorMsgStr += "气体ID不能为空；";
        //                isHaveNoInputValue = true;
        //            }
        //            if ("底气".Equals(en.IsBottomGas))
        //            {
        //                en.IsBottomGas = "1";
        //            }
        //            else
        //            {
        //                en.IsBottomGas = "0";
        //            }
        //            switch (en.CusUnit)
        //            {
        //                case "ppm":
        //                    en.CusUnit = "0";
        //                    break;
        //                case "%":
        //                    en.CusUnit = "1";
        //                    break;
        //                case "mg/m3":
        //                    en.CusUnit = "2";
        //                    break;
        //                case "lel":
        //                    en.CusUnit = "3";
        //                    break;
        //                default:
        //                    en.CusUnit = "0";
        //                    break;

        //            }
        //            CalculateConcentration(en);
        //            if (isHaveNoInputValue) // 若必填项有值未填
        //            {
        //                enlist.Remove(enlist[i]);
        //                errorMsg.AppendLine(errorMsgStr);
        //            }
        //        }
        //        #endregion

        //        // 3.TODO：对List集合进行持久化存储操作。如：存储到数据库
        //        enlist.ForEach(li => DALSession.Current.CM_QuotationDetailDetailDAL.Add(li));
        //        DALSession.Current.CM_QuotationDetailDetailDAL.SaveChanges();
        //        // 4.返回操作结果
        //        bool isSuccess = false;
        //        if (errorMsg.Length == 0)
        //        {
        //            isSuccess = true; // 若错误信息成都为空，表示无错误信息
        //            errorMsg.Append("数据导入成功,共计导入" + enlist.Count() + "条。");
        //        }
        //        Response.Write(JsonHelper.toDefaultMsg(isSuccess, errorMsg.ToString())); // 返回Json格式的内容
        //    }
        //    catch (Exception ex)
        //    {
        //        throw ex;
        //    }
        //    finally
        //    {
        //        File.Delete(filePath);
        //    }
        //}

        /**
         * 其它函数
         **/

        /// <summary>
        /// 通过报价单ID或者合同ID获取所有细则与技术参数,包含气体组分浓度
        /// </summary>
        public void GetAllProductDetailByID()
        {
            //根据报价单ID获取相关信息
            if (Request.Form["quotID"] != null && Request.Form["quotID"] != "")
            {
                int[] quotID;
                if (Request.Form["quotID"].Contains("["))
                {
                    //多个报价单
                    quotID = JsonConvert.DeserializeObject<int[]>(Request.Form["quotID"]);
                }
                else
                {
                    //只选了一个报价单
                    quotID = new int[1];
                    quotID[0] = JsonConvert.DeserializeObject<int>(Request.Form["quotID"]);
                }

                List<View_PM_ProductOrderDetail> listAll = new List<View_PM_ProductOrderDetail>();
                foreach (var id in quotID)
                {
                    var list = DALSession.Current.View_PM_ProductOrderDetailDAL.GetListBy(c => c.QuotationID == id);
                    listAll.AddRange(list);
                }
                Response.Write(JsonHelper.toJson(listAll));
                return;
            }
            //根据合同ID获取相关信息
            if (Request.Form["contID"] != null && Request.Form["contID"] != "")
            {
                int contID = Convert.ToInt32(Request.Form["contID"]);
                //先查出对应的报价单
                var list = DALSession.Current.CM_QuotationDAL.GetListBy(c => c.ContractID == contID).ToList();
                List<View_PM_ProductOrderDetail> listAll = new List<View_PM_ProductOrderDetail>();
                foreach (var item in list)
                {
                    var glist = DALSession.Current.View_PM_ProductOrderDetailDAL.GetListBy(c => c.QuotationID == item.ID);
                    listAll.AddRange(glist);
                }
                Response.Write(JsonHelper.toJson(listAll));
            }
        }

        /// <summary>
        /// 根据合同ID获取所有产品信息，用于打印
        /// </summary>
        public void GetAllProductDetailForContractPrint()
        {
            if (Request.Form["contID"] != null && Request.Form["contID"] != "")
            {
                int contID = Convert.ToInt32(Request.Form["contID"]);
                //先查出对应的报价单
                var list = DALSession.Current.CM_QuotationDAL.GetListBy(c => c.ContractID == contID).ToList();
                //获取发货地址
                HashSet<int> addressSet = new HashSet<int>();
                list.ForEach(li =>
                {
                    if (null != li.CusRecAddID && "" != li.CusRecAddID.ToString())
                    {
                        addressSet.Add(Convert.ToInt32(li.CusRecAddID));
                    }
                });
                String address = "";
                foreach (int addID in addressSet)
                {
                    if (0 != addID)
                    {
                        address += DALSession.Current.BD_CompanyAddressDAL.GetListBy(cd => cd.ID == addID).FirstOrDefault().Address + ";";
                    }
                }
                //查询所有产品信息
                List<View_PM_ProductOrderDetail> listAll = new List<View_PM_ProductOrderDetail>();
                foreach (var item in list)
                {
                    var glist = DALSession.Current.View_PM_ProductOrderDetailDAL.GetListBy(c => c.QuotationID == item.ID);
                    listAll.AddRange(glist);
                }
                //处理技术参数，使用客户单位
                listAll.ForEach(li =>
                {
                    String cusTechParam = "";
                    String bottomGasParam = "";
                    var tempList = DALSession.Current.CM_QuotationDetailDetailDAL.GetListBy(qDD => qDD.QuotationDetailID == li.QuotationDetailID);
                    if ("0".Equals(DALSession.Current.CM_QuotationDetailDAL.GetListBy(qd => qd.ID == li.QuotationDetailID).FirstOrDefault().IsPureGas))
                    {
                        //混合气体处理
                        tempList.ForEach(tp =>
                        {
                            if ("1".Equals(tp.IsBottomGas))
                            {
                                bottomGasParam = DALSession.Current.BD_GasInfoDAL.GetListBy(ga => ga.ID == tp.GasID).FirstOrDefault().GasEngName + ":余量";
                            }
                            else
                            {
                                cusTechParam += DALSession.Current.BD_GasInfoDAL.GetListBy(ga => ga.ID == tp.GasID).FirstOrDefault().GasEngName + ":" + tp.CusConcen.ToString("0.##") + GetUnitString(tp.CusUnit) + ";";
                            }
                        });
                    }
                    else
                    {
                        //纯气处理
                        tempList.ForEach(tp =>
                        {
                            if ("1".Equals(tp.IsBottomGas))
                            {
                                bottomGasParam = DALSession.Current.BD_GasInfoDAL.GetListBy(ga => ga.ID == tp.GasID).FirstOrDefault().GasEngName + ":" + tp.CusConcen.ToString("0.####") + GetUnitString(tp.CusUnit);
                            }
                        });
                    }
                    cusTechParam += bottomGasParam;
                    li.TechParams = cusTechParam;
                });
                Response.Write(JsonHelper.toJson(new { listAll = listAll, address = address }));
            }
        }

        public String GetUnitString(String code)
        {
            String res = "";
            if (String.IsNullOrEmpty(code))
            {
                res = "ppm";
            }
            else
            {
                switch (code)
                {
                    case "0":
                        res = "ppm";
                        break;
                    case "1":
                        res = "%";
                        break;
                    case "2":
                        res = "mg/m3";
                        break;
                    default:
                        res = "ppm";
                        break;
                }
            }
            return res;
        }

        /// <summary>
        /// 根据QuotationID和单位将每个产品的技术参数拼接为一个字符串
        /// 前台调用
        /// </summary>
        public void JoinTechParam()
        {
            int QuotationID = Commons.String2Int32(Request.Form["QuotationID"]);
            int unit = Commons.String2Int32(Request.Form["unit"]);
            UnitSelector enumUnit = UnitSelector.PPM;
            switch (unit)
            {
                case (0):
                    enumUnit = UnitSelector.PPM;
                    break;
                case (1):
                    enumUnit = UnitSelector.Percent;
                    break;
                case (2):
                    enumUnit = UnitSelector.MGM3;
                    break;
                default:
                    break;
            }
            bool success = JoinTechParamByQuotationID(QuotationID, enumUnit);
            Response.Write(JsonHelper.toDefaultMsg(success));
        }

        /// <summary>
        /// 根据QuotationID将每个产品的技术参数拼接为一个字符串
        /// </summary>
        /// <param name="QuotationID"></param>
        /// <returns></returns>
        public Boolean JoinTechParamByQuotationID(int QuotationID, UnitSelector unit)
        {
            Boolean flag = true;
            List<CM_QuotationDetail> pList = DALSession.Current.CM_QuotationDetailDAL.GetListBy(p => p.QuotationID == QuotationID).ToList();
            if (pList.Count > 0)
            {
                pList.ForEach(pDetail =>
                {
                    String tempStr = "";
                    if ((tempStr = GetTechParamsToString(pDetail.ID, unit)) == "")
                    {
                        flag = false;
                    }
                    else
                    {
                        pDetail.TechParams = tempStr;
                    }
                });
            }
            else
            {
                flag = false;
            }
            if (flag)
            {
                pList.ForEach(pTemp =>
                {
                    DALSession.Current.CM_QuotationDetailDAL.ModifyAllModel(pTemp);
                });
                DALSession.Current.CM_QuotationDetailDAL.SaveChanges();
            }
            return flag;
        }

        /// <summary>
        /// 根据产品细则ID和需求的单位类型，获得产品细则参数字符串
        /// </summary>
        /// <param name="prodDetailID"></param>
        /// <param name="unitType"></param>
        /// <returns></returns>
        public String GetTechParamsToString(int prodDetailID, UnitSelector unitType)
        {
            StringBuilder res = new StringBuilder();
            List<View_CM_QuotationDetailDetail> list = DALSession.Current.View_CM_QuotationDetailDetailDAL.GetListBy(p => p.QuotationDetailID == prodDetailID).ToList();
            if (list.Count() == 0)
            {
                return res.ToString();
            }
            int bottomGasCount = 0;
            try
            {
                list.ForEach(pList =>
                {
                    String str = "";
                    Double concentrate = (double)pList.Concentration;
                    switch (unitType)
                    {
                        case UnitSelector.Percent:
                            str = (concentrate / 10000).ToString() + "%";
                            break;
                        case UnitSelector.MGM3:
                            str = PPMToMGCM(concentrate, (double)pList.GasWeight);
                            break;
                        case UnitSelector.PPM:
                            str = concentrate.ToString() + "ppm";
                            break;
                    };
                    //如果是底气而且不是纯气，则显示余量
                    if ("1".Equals(pList.IsBottomGas) && list.Count > 1)
                    {
                        str = "余量";
                    }

                    res.Append(pList.GasEngName + ":" + str + ";");
                    if ("1".Equals(pList.IsBottomGas))
                    {
                        bottomGasCount += 1;
                    }
                });
            }
            catch (Exception)
            {
                return res.Clear().ToString();
            }
            if (1 != bottomGasCount)
            {
                res.Clear();
            }
            return res.ToString();
        }

        /// <summary>
        /// PPM到MGM3的转换公式
        /// </summary>
        /// <param name="con">浓度ppm</param>
        /// <param name="weight">分子量</param>
        /// <returns></returns>
        public String PPMToMGCM(Double con, Double weight)
        {
            String res = "";
            res += Math.Round(con * weight / 22.4, 2).ToString() + "mg/m3";
            return res;
        }

        /// <summary>
        /// PPM到MGCM3的转换公式
        /// </summary>
        /// <param name="con"></param>
        /// <param name="weight"></param>
        /// <returns></returns>
        public String PPMToMGCMNoN(Double con, Double weight)
        {
            String res = "";
            res += Math.Round(con * weight / 22.4, 2).ToString();
            return res;
        }

        /// <summary>
        /// 根据报价单细则ID获取纯气气体的国标信息
        /// </summary>
        public void GetProdTechAndGBInfoByID()
        {
            int Id = Commons.String2Int32(Request["Id"]);
            int gasId = DALSession.Current.CM_QuotationDetailDetailDAL.GetListBy(li => li.QuotationDetailID == Id).FirstOrDefault().GasID;
            string temp;
            int gbId = Commons.String2Int32("" == (temp = DALSession.Current.BD_GasInfoDAL.GetListBy(li => li.ID == gasId).FirstOrDefault().GBID.ToString()) ? "0" : temp);
            BD_GBInfo gb = DALSession.Current.BD_GBInfoDAL.GetListBy(li => li.ID == gbId).FirstOrDefault();
            Response.Write(JsonHelper.toJson(gb));
            return;
        }

        /// <summary>
        /// 根据报价单细则ID获取相同产品的国标信息
        /// </summary>
        public void GetSameGBInfoByID()
        {
            int Id = Commons.String2Int32(Request["Id"]);
            var lastMain = DALSession.Current.PM_BottleProductionDAL.GetListBy(c => c.QuotationDetailID == Id).OrderByDescending(c => c.ID).FirstOrDefault();
            if (lastMain == null)
            {
                Response.Write(JsonHelper.toJson(new { msg = false }));
                return;
            }
            BD_GBInfo gb = DALSession.Current.BD_GBInfoDAL.GetListBy(li => li.ID == lastMain.GBID).FirstOrDefault();
            Response.Write(JsonHelper.toJson(new { msg = true, per = gb }));
        }

        /**
         * 传入实体校验函数
         * **/

        ///校验报价单实体是否符合要求
        public Boolean checkQuotation(CM_Quotation q, String msg)
        {
            Boolean res = true;
            if (String.IsNullOrEmpty(q.Code))
            {
                msg = "合同编号不能为空！";
                res = false;
            }
            else if (String.IsNullOrEmpty(q.CustomerID.ToString()))
            {
                msg = "客户不能为空！";
                res = false;
            }
            else if (String.IsNullOrEmpty(q.SupplierID.ToString()))
            {
                msg = "供应商不能为空！";
                res = false;
            }
            return res;
        }

        /// <summary>
        /// 校验报价单细则实体是否符合要求
        /// </summary>
        /// <param name="qD"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public Boolean checkQuotationDetail(CM_QuotationDetail qD, String msg)
        {
            Boolean res = true;
            if (String.IsNullOrEmpty(qD.QuotationID.ToString()))
            {
                res = false;
                msg = "报价单ID不能为空！";
            }
            if (!ChangeEmptyToNull(qD))
            {
                res = false;
            }
            return res;
        }

        /// <summary>
        /// 校验产品技术参数实体是否符合要求
        /// </summary>
        /// <param name="qDD"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public Boolean checkQuotationDetailDetail(CM_QuotationDetailDetail qDD, String msg)
        {
            Boolean res = true;
            if (String.IsNullOrEmpty(qDD.QuotationDetailID.ToString()))
            {
                res = false;
                msg = "产品细则ID不能为空！";
            }
            else if (String.IsNullOrEmpty(qDD.GasID.ToString()))
            {
                res = false;
                msg = "气体ID不能为空！";
            }
            else if (String.IsNullOrEmpty(qDD.CusConcen.ToString()))
            {
                res = false;
                msg = "组分浓度不能为空！";
            }
            else if (String.IsNullOrEmpty(qDD.CusUnit.ToString()))
            {
                msg = "组分浓度单位不能为空";
            }
            if (!ChangeEmptyToNull(qDD))
            {
                res = false;
            }
            return res;
        }

        ///产品及技术参数空字符串转换为Null
        ///产品信息转换
        public Boolean ChangeEmptyToNull(CM_QuotationDetail qd)
        {
            Boolean res = false;
            if (null != qd)
            {
                if ("".Equals(qd.OrderCode))
                {
                    qd.OrderCode = null;
                }
                if ("".Equals(qd.StockCode))
                {
                    qd.StockCode = null;
                }
                if ("".Equals(qd.PurchaseType))
                {
                    qd.PurchaseType = null;
                }
                if ("".Equals(qd.ApplyPerson))
                {
                    qd.ApplyPerson = null;
                }
                if ("".Equals(qd.Note))
                {
                    qd.Note = null;
                }
                res = true;
            }
            return res;
        }
        //技术参数转换
        public Boolean ChangeEmptyToNull(CM_QuotationDetailDetail qdd)
        {
            Boolean res = false;
            if (null != qdd)
            {
                if ("".Equals(qdd.Note)) qdd.Note = null;
                res = true;
            }
            return res;
        }

        /// <summary>
        /// 根据客户浓度计算ppm浓度
        /// </summary>
        /// <param name="qdd"></param>
        public void CalculateConcentration(CM_QuotationDetailDetail qdd)
        {
            BD_GasInfo gas = DALSession.Current.BD_GasInfoDAL.GetListBy(ga => ga.ID == qdd.GasID).FirstOrDefault();
            if (null != gas)
            {
                switch (qdd.CusUnit)
                {
                    case "0":
                        qdd.Concentration = qdd.CusConcen;
                        break;
                    case "1":
                        qdd.Concentration = qdd.CusConcen * 10000;
                        break;
                    case "2":
                        qdd.Concentration = qdd.CusConcen * 22.4m / (decimal)gas.GasWeight;
                        break;
                    case "3":
                        qdd.Concentration = qdd.CusConcen * (null == gas.Lel ? 0m : (decimal)gas.Lel) * 10000;
                        break;
                    default:
                        break;
                }
            }
        }

        /// <summary>
        /// 根据报价单ID获取相关信息，用于打印报价单
        /// </summary>
        public void GetQuotCustomerByID()
        {
            if (Request["id"] != null)
            {
                int quotID = Commons.String2Int32(Request["id"]);
                var perQuot = DALSession.Current.CM_QuotationDAL.GetListBy(c => c.ID == quotID).FirstOrDefault();
                var perCus = DALSession.Current.BD_CompanyInfoDAL.GetListBy(c => c.ID == perQuot.CustomerID).FirstOrDefault();

                Response.Write(JsonHelper.toJson(
                    new
                    {
                        Code = perQuot.Code,
                        SignDate = perQuot.Date,
                        Note = perQuot.Note,
                        ComName = perCus.ComName,
                        ComAddress = perCus.ComAddress,
                        Phone = perCus.Phone,
                        Fax = perCus.Fax,
                        MobilePhone = perCus.MobilePhone,
                        Email = perCus.Mail,
                        Person = perCus.Person
                    }));
            }
        }

        /// <summary>
        /// 根据报价单ID获取所有产品信息，用于打印
        /// </summary>
        public void GetAllProductDetailForQuotPrint()
        {
            if (Request.Form["quotID"] != null && Request.Form["quotID"] != "")
            {
                int quotID = Convert.ToInt32(Request.Form["quotID"]);
                var glist = DALSession.Current.View_PM_ProductOrderDetailDAL.GetListBy(c => c.QuotationID == quotID);
                //处理技术参数，使用客户单位
                glist.ForEach(li =>
                {
                    String cusTechParam = "";
                    String bottomGasParam = "";
                    var tempList = DALSession.Current.CM_QuotationDetailDetailDAL.GetListBy(qDD => qDD.QuotationDetailID == li.QuotationDetailID);
                    if ("0".Equals(DALSession.Current.CM_QuotationDetailDAL.GetListBy(qd => qd.ID == li.QuotationDetailID).FirstOrDefault().IsPureGas))
                    {
                        //混合气体处理
                        tempList.ForEach(tp =>
                        {
                            if ("1".Equals(tp.IsBottomGas))
                            {
                                bottomGasParam = DALSession.Current.BD_GasInfoDAL.GetListBy(ga => ga.ID == tp.GasID).FirstOrDefault().GasEngName + ":余量";
                            }
                            else
                            {
                                cusTechParam += DALSession.Current.BD_GasInfoDAL.GetListBy(ga => ga.ID == tp.GasID).FirstOrDefault().GasEngName + ":" + tp.CusConcen.ToString("0.##") + GetUnitString(tp.CusUnit) + ";";
                            }
                        });
                    }
                    else
                    {
                        //纯气处理
                        tempList.ForEach(tp =>
                        {
                            if ("1".Equals(tp.IsBottomGas))
                            {
                                bottomGasParam = DALSession.Current.BD_GasInfoDAL.GetListBy(ga => ga.ID == tp.GasID).FirstOrDefault().GasEngName + ":" + tp.CusConcen.ToString("0.####") + GetUnitString(tp.CusUnit);
                            }
                        });
                    }
                    cusTechParam += bottomGasParam;
                    li.TechParams = cusTechParam;
                });
                
                
                Response.Write(JsonHelper.toJson(glist));
            }
        }
    }
}